package com.youthfilmic.yuejian.controller;

import com.aliyun.oss.OSS;
import com.youthfilmic.yuejian.dao.*;
import com.youthfilmic.yuejian.domain.*;
import com.youthfilmic.yuejian.service.ApplicationService;
import com.youthfilmic.yuejian.service.SubjectService;
import com.youthfilmic.yuejian.service.UserService;
import com.youthfilmic.yuejian.util.MobileCodeUtil;
import com.youthfilmic.yuejian.util.OSSUtil;
import com.youthfilmic.yuejian.util.QiniuAPI;
import com.youthfilmic.yuejian.util.SaveImageFromUrlThread;
import com.youthfilmic.yuejian.weixin.core.TokenSystem;
import net.sf.json.JSONObject;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by youweixi on 15/10/7.
 * 用户中心的controller
 */
@Controller
@RequestMapping("/main/user")
public class UserController {
    @Resource
    private CertificationDao certificationDao;
    @Resource
    private SubjectDao subjectDao;
    @Resource
    private UserDao userDao;
    @Resource
    private ApplicationDao applicationDao;
    @Autowired
    private ApplicationService applicationService;
    @Resource
    private AccountDao accountDao;
    @Autowired
    private UserService userService;
    @Autowired
    private SubjectService subjectService;

    @ModelAttribute("userId")
    private Long getUserId(HttpSession session){
        Long userId = (Long) session.getAttribute("userId");
        return userId;
    }


    @RequestMapping("/index")
    public String showIndex(
            @ModelAttribute("userId") Long userId,
            Model model
    ){
        if(userId == null) return "redirect:/main/index";

        User user = userDao.findOne(userId);
        model.addAttribute("user",user);
        return "main/user/index";
    }


    @RequestMapping("/profile/edit")
    public String showProfileEdit(
            @ModelAttribute("userId") Long userId,
            Model model
    ){
        User user = userDao.findOne(userId);
        model.addAttribute("user",user);
        model.addAttribute("sexMap" , DomainInfo.getSexMap());
        model.addAttribute("cityMap" , DomainInfo.getCityMap());
        return "main/user/profile/edit";
    }

    @RequestMapping("/certification")
    public String showCertification(Model model ,
                                    @ModelAttribute("userId") Long userId,
                                    @RequestParam(value="again" , required = false) Integer again){

        Certification c = certificationDao.findByUserId(userId);
        //没有提交过审核
        if (c == null){
            model.addAttribute("certification" , new Certification());
            model.addAttribute("cityMap", DomainInfo.getCityMap());
            model.addAttribute("jobMap", DomainInfo.getJobTimeMap());
            return "main/user/certification/certification";
        }else{
                //等待审核
            if (c.getStatus() == Certification.STATUS_WAIT_FOR_CERTIFICATE){
                model.addAttribute("postAt" , c.getPostAt());
                return "main/user/certification/certification-pending";
                //审核成功
            }else if (c.getStatus() == Certification.STATUS_SUCCEED){
                model.addAttribute("postAt" , c.getPostAt());
                model.addAttribute("handleAt" , c.getHandleAt());
                return "main/user/certification/certification-succeed";
                //审核失败
            }else if (c.getStatus() == Certification.STATUS_FAILED){
                //再次填写
                if (again != null && again == 1){
                    //再次填写
                    model.addAttribute("certification" , c);
                    model.addAttribute("cityMap", DomainInfo.getCityMap());
                    model.addAttribute("jobMap", DomainInfo.getJobTimeMap());
                    return "main/user/certification/certification";
                }else{
                    //通知审核失败
                    model.addAttribute("reason",c.getReason());
                    model.addAttribute("postAt" , c.getPostAt());
                    model.addAttribute("handleAt" , c.getHandleAt());
                    return "main/user/certification/certification-failed";
                }
            }
        }
        return null;
    }

    @RequestMapping(value="/certification.do" , method = RequestMethod.POST)
    public String doCertification(
            Certification certification,
            //@RequestParam(value="file" , required = false) MultipartFile image,
            @RequestParam(value="mediaId" , required = false) String mediaId,
            @ModelAttribute("userId") Long userId
    ){
        User user = userDao.findOne(userId);
        Certification c = certificationDao.findByUserId(userId);
        //注意这里持久化一下
        if (c != null) certification.setId(c.getId());
        //通用设置一下内容
        if(mediaId != null && !"".equals(mediaId)){
            String imageUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+TokenSystem.getTokenValue()+"&media_id=" + mediaId;
            QiniuAPI.fetch(imageUrl , QiniuAPI.getFileKey(0,2));
        }
        certification.setStatus(Certification.STATUS_WAIT_FOR_CERTIFICATE);
        certification.setApplicationAccepted(false);
        certification.setPostAt(new Date());
        certification.setUserId(userId);
        certification.setUser(user);
        certificationDao.save(certification);
        return "redirect:/main/user/certification";
    }

    /**
     * 还没有实名认证，操作不能执行
     * */
    @RequestMapping("/certification/not_certificated")
    public String showNotCertificatedPage(){
        return "main/user/certification/not-certificated";
    }


    @RequestMapping("/subject/post")
     public String showSubjectPost(
            Model model,
            @ModelAttribute("userId") Long userId){
        //如果没有实名认证，则跳转页面提示
        User user = userDao.findOne(userId);
        if (!user.isCertificationAccepted()){
            return "redirect:/main/user/certification/not_certificated";
        }
        model.addAttribute("subject", new Subject());
        model.addAttribute("durationMap", DomainInfo.getDurationMap());
        model.addAttribute("typeMap", DomainInfo.getSubjectTypeMap());
        return "main/user/subject/new-subject";
    }

    @RequestMapping("/subject/post.do")
    public String doSubjectPost(
            Subject subject,
            @ModelAttribute("userId") Long userId
    ){
        //创建新的话题
        subjectService.createSubject(userId, subject);
        return "redirect:/main/user/subject/post_succeed";
    }

    /**
     * 话题发布成功
     * */
    @RequestMapping("/subject/post_succeed")
    public String showPostSucceed(){
        return "main/user/subject/post_succeed";
    }

    @RequestMapping("/subject/list")
    public String showSubjectList(Model model, @ModelAttribute("userId") Long userId
    ){
        Page<Subject> page = subjectDao.findByUserId(userId, new PageRequest(0, 10, new Sort(Sort.Direction.DESC, "postAt")));
        model.addAttribute("subjects", page.getContent());
        return "main/user/subject/my-subject";
    }

    @RequestMapping("/account/index")
    public String showAccountIndex(
            @ModelAttribute("userId") Long userId,
            Model model
    ){
        User user = userDao.findOne(userId);
        //获取账户的唯一方法
        Account account = userService.getAccount(user.getId());
        model.addAttribute("account" , account);
        model.addAttribute("user" , user);
        return "main/user/account/money";
    }

    @RequestMapping("/account/draw")
    public String draw (
            @ModelAttribute("userId") Long userId,
            Model model){
        User user = userDao.findOne(userId);
        //获取账户的唯一方法
        Account account = userService.getAccount(user.getId());
        model.addAttribute("account" , account);
        model.addAttribute("user" , user);
        return "main/user/account/draw-money";
    }

    @RequestMapping("/application/mine")
    public String showMineApplication(
            @RequestParam(value="status" , required = false) Integer status,
            @ModelAttribute("userId") Long userId,
            Model model
    ){
        Page<Application> page = null;
        if (status == null) status = 0;
        if (status == 0){
            model.addAttribute("status" , 0);
            page = applicationDao.findByUserIdForRunning(userId , new PageRequest(0 , 10 , new Sort(Sort.Direction.DESC , "postAt")));
        }else if (status == 1){
            model.addAttribute("status" , 1);
            page = applicationDao.findByUserIdForComment(userId, new PageRequest(0, 10, new Sort(Sort.Direction.DESC, "postAt")));
        }else if (status == 2){
            model.addAttribute("status" , 2);
            page = applicationDao.findByUserIdForCompeted(userId , new PageRequest(0 , 10 , new Sort(Sort.Direction.DESC , "postAt")));
        }else{
            status = 0;
            model.addAttribute("status" , 0);
            page = applicationDao.findByUserIdForRunning(userId, new PageRequest(0, 10, new Sort(Sort.Direction.DESC, "postAt")));
        }
        model.addAttribute("applications", page.getContent());
        return "main/user/application/mine";
    }

    @RequestMapping("/application/tome")
    public String showTomeApplication(
            @RequestParam(value="status" , required = false) Integer status,
            @ModelAttribute("userId") Long userId,
            Model model
    ){
        Page<Application> page = null;
        if (status == null) status = 0;
        if (status == 0) {
            model.addAttribute("status", 0);
            page = applicationDao.findByStarIdForRunning(userId, new PageRequest(0, 10, new Sort(Sort.Direction.DESC, "postAt")));
        }else if (status == 1){
            model.addAttribute("status" , 1);
            page = applicationDao.findByStarIdForComment(userId, new PageRequest(0, 10, new Sort(Sort.Direction.DESC, "postAt")));
        }else if (status == 2) {
            model.addAttribute("status", 2);
            page = applicationDao.findByStarIdForCompeted(userId, new PageRequest(0, 10, new Sort(Sort.Direction.DESC, "postAt")));
        }else{
            status = 0;
            model.addAttribute("status", 0);
            page = applicationDao.findByStarIdForRunning(userId, new PageRequest(0, 10, new Sort(Sort.Direction.DESC, "postAt")));
        }
        model.addAttribute("applications" , page.getContent());
        return "main/user/application/to-me";
    }

    @RequestMapping("/application/tome/handle")
    public String handleTomeApplication(
            @RequestParam(value="status" , required = false) Integer status,
            @ModelAttribute("userId") Long userId,
            @RequestParam(value="applicationId" , required = false) Long applicationId
    ){
        if (status != null && applicationId != null){
            if (status == 1){
                try {
                    applicationService.handleApplication(applicationId , userId , 1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if (status == -1){
                try {
                    applicationService.handleApplication(applicationId , userId , -1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return "redirect:/main/user/application/tome";
    }



    /**
     * 牛人查看约见申请
     * */
    @RequestMapping("/application/tome/single")
    public String showTomeSingle(
            @RequestParam("applicationId") Long applicationId,
            @ModelAttribute("userId") Long userId,
            Model model
    ){
        Application a = applicationDao.findOne(applicationId);
        //不是自己的被约申请或者申请还未付款
        if (a.getStarId() != userId || a.getStatus() == 0){
            return "redirect:/main/user/application/tome";
        }
        model.addAttribute("application" , a);
        return "main/user/application/single-tome";
    }

    /**
     * 牛人查看约见申请
     * */
    @RequestMapping("/application/mine/single")
    public String showMineSingle(
            @RequestParam("applicationId") Long applicationId,
            @ModelAttribute("userId") Long userId,
            Model model
    ){
        Application a = applicationDao.findOne(applicationId);
        //不是自己的被约申请或者申请还未付款
        if (a.getUserId() != userId){
            return "redirect:/main/user/application/mine";
        }
        model.addAttribute("application" , a);
        return "main/user/application/single-mine";
    }

    /**
     * 普通用户评价牛人
     * */
    @RequestMapping("/application/mine/comment")
    public String commentToStar(
            @RequestParam(value="applicationId") Long applicationId,
            @ModelAttribute("userId") Long userId,
            Model model
    ){
        Application a = applicationDao.findOne(applicationId);
        if (a.getUserId() != userId){//不是自己的约见请求
            //跳转回自己的列表
            return "redirect:/main/user/application/mine?status=1";
        }
        model.addAttribute("application",a);
        Comment comment = new Comment();
        comment.setContent("非常满意~希望以后多多交流~");
        comment.setEvaluation(5);
        model.addAttribute("comment",comment);
        return "main/user/application/comment-to-star";
    }

    /**
     * 评价牛人
     * */
    @RequestMapping("/application/mine/comment.do")
    public String doCommentToStar(
            @RequestParam(value="applicationId") Long applicationId,
            @ModelAttribute("userId") Long userId,
            Comment comment,
            Model model
    ){
        try {
            applicationService.userCommentForApplication(applicationId , userId , comment);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/main/user/application/mine?status=1";
    }

    /**
     * 牛人评价普通用户
     * */
    @RequestMapping("/application/tome/comment")
    public String commentToUser(
            @RequestParam(value="applicationId") Long applicationId,
            @ModelAttribute("userId") Long userId,
            Model model
    ){
        Application a = applicationDao.findOne(applicationId);
        if (a.getStarId() != userId){//不是自己的约见请求
            //跳转回列表
            return "redirect:/main/user/application/tome?status=1";
        }
        model.addAttribute("application",a);
        Comment comment = new Comment();
        comment.setContent("很高兴看到我对您有帮助~");
        comment.setEvaluation(5);
        model.addAttribute("comment",comment);
        return "main/user/application/comment-to-user";
    }

    /**
     * 牛人评价普通用户
     * */
    @RequestMapping("/application/tome/comment.do")
    public String doCommentToUser(
            @RequestParam(value="applicationId") Long applicationId,
            @ModelAttribute("userId") Long userId,
            Comment comment,
            Model model
    ){
        try {
            applicationService.starCommentForApplication(applicationId, userId, comment);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/main/user/application/tome?status=1";
    }

    @RequestMapping("/subject/desire")
    public String showesireApplication(){
        return "main/user/subject/desire-subject";
    }







}
